<?php

namespace app\mobile\controller;

use think\Controller;
use think\Request;
use Myredis\Myredis;
use think\Db;
use think\Session;
class login extends Controller
{

    public function index()
    {
        if (empty(Request::instance()->session('uid'))) {
            return view('login');
        } else {
            $userinfo = Db::table('xo_user')->field('pwd', true)->find(Request::instance()->session('uid'));
            return view('personal', [
                'userinfo' => $userinfo
            ]);
        }

    }

    /**
     * 处理账号密码登录
     * @return \think\response\View
     */
    public function dologin(Request $request)
    {
        //验证数据是否来自post传输方式
        if (!Request::instance()->isPost()) {
            return $this->error('小伙子迷路了呦', url('mobile/login/index'));
        }
        $tel = Request::instance()->post('tel');
        $pwd = Request::instance()->post('pwd');
        $data = Myredis::hget('userLogin', $tel);
        $info = [
            'tel' => $tel,
            'pwd' => md5($pwd),
            'status' => 1
        ];
        //验证数据与redis中的数据是否一致
        if ($data && ($tel == $data['tel'] && md5($pwd) == $data['pwd'] && $data['status'] == 1)) {
            Db::table('xo_user')->where('tel', $tel)->update(['login_time' => time()]);
            //redis 查询出数据 存入session 登录成功
            Session::set('tel', $data['tel']);
            //生成一个唯一的token存在session和redis中
            $token = time() . mt_rand(1, 1000000);
            Session::set('token', $token);
            MyRedis::set($tel . 'token', $token);
            return $this->success('登录成功', url('mobile/index/index'));
        } else {
            //数据与redis不一致则查询数据库
            $res = Db::table('xo_user')->where($info)->field(['nickname', 'id', 'icon'])->find();
            if ($res) {
                //数据库能查到则存入session 将redis更新  登录成功
                Session::set('name', $res['nickname']);
                Session::set('uid', $res['id']);
                Session::set('icon', $res['icon']);
                Session::set('tel', $res['tel']);
                Myredis::hset('userLogin', $tel, $info);
                Db::table('xo_user')->where('tel', $tel)->update(['login_time' => time()]);
                $token = time() . mt_rand(1, 1000000);
                Session::set('token', $token);
                MyRedis::set($tel . 'token', $token);
                return $this->success('登录成功', url('mobile/index/index'));
            } else {
                //redis和数据库都查询不到则失败
                return $this->error('登录失败');
            }
        }
    }


    /**
     * 退出登录
     */
    public function outlogin()
    {
        $data = Session::clear();
        $res = Myredis::del(Request::instance()->session('tel') . 'token');
        if ($data && $res) {
            return $this->success('退出成功', url('mobile/index/index'));
        } else {
            return $this->success('退出成功', url('mobile/index/index'));
        }
    }
}